package jianzhioffer.tree;

import algorithm.model.TreeNode;

/**
 * 对称的二叉树
 * 判断树是否对称：是否和自己的镜像相等
 * Created by yzy on 2020-06-16 20:12
 */
public class SymmetrialTree {

    public static void main(String[] args) {
        TreeNode t = TreeNode.getTreeNode(new Integer[]{1,2,2,3,4,4,3});
        TreeNode t2 = TreeNode.getTreeNode(new Integer[]{1,2,2,3,4,4,3,2});
        System.out.println(isSymmetrical(t));
        System.out.println(isSymmetrical(t2));
    }

    /**
     * root为null时，结果是true
     * 然后对比两个子树是否是对称的就可以了。
     * @param pRoot
     * @return
     */
    static boolean isSymmetrical(TreeNode pRoot){
        if(pRoot==null){
            return true;
        }
        return symmetrialTreeVal(pRoot.left, pRoot.right);
    }

    private static boolean symmetrialTreeVal(TreeNode left, TreeNode right){
        if(left==null && right ==null){
            return true;
        }
        if(left != null && right != null){
            return left.val==right.val && symmetrialTreeVal(left.left, right.right) && symmetrialTreeVal(left.right, right.left);
        }
        return false;
    }
}
